#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>

#include "list.h"					  /* use the SimCList library */
#include "utils.h"

#define TRUE 1
#define FALSE 0

int equint(const void *a,const void *b) {
/*	printf("equ ? %8d vs %8d\n",*(int *)a , *(int *)b); */
	return( (*(int *)a == *(int *)b)?TRUE:FALSE );
}

int compint(const void *a,const void *b) {
/*	printf("%8d vs %8d\n",*(int *)a , *(int *)b); */
	return( (*(int *)a < *(int *)b)?FALSE:TRUE );
}

int main(int argc,char **argv)
{
	list *mylist,*dlist;	
	int userval;
	int i,*rnum;
	listIter *iter;
	listNode *node;
	struct timeval tmv;

	mylist = listCreate();
	mylist->match = equint;
	mylist->free = free;

      if ( argc < 1 ) { printf("with cmd-line param\n"); exit(0); }
	userval = atol(argv[1]);

	for (i = 0; i<userval ; i++){
		rnum = calloc(1,sizeof(int));
		*rnum = randi(10000);
		listAddNodeHead(mylist, rnum);
		}
	printf("\n 1st holds %u elements.\n", listLength(mylist));

	for (i = 0; i<10; i++){
		rnum = calloc(1,sizeof(int));
		*rnum = 1000;
		listAddNodeHead(mylist, rnum);
		}
	printf("\n 2nd add 10 holds %u elements.\n", listLength(mylist));

	list_qsort(mylist,compint);
	printf("\n 3rd sorted holds %u elements.\n", listLength(mylist));

	for (i = 0; i<10; i++){
		rnum = calloc(1,sizeof(int));
		*rnum = randi(10000);
		list_binsert(mylist, rnum,compint);
		}

	printf("\n4th final holds %u elements.\n", listLength(mylist));

        iter=listGetIterator(mylist,AL_START_HEAD);
	i = 0;
	while ((node = listNext(iter)) != NULL) {
		;;
		printf("%8d", *(int *)node->value);
		if(++i > 50 ) break;
	}
	printf("\n");
	listReleaseIterator(iter);

	printf("\nbegin DupByKey %u elements.\n", listLength(mylist));
	rnum = calloc(1,sizeof(int));
	*rnum=1000;
	tic(&tmv);
	dlist = listDupByKey(mylist, rnum, compint);
	toc(&tmv);
   
	i = 0;
	node = dlist->head;
	while( node!=NULL ) {
		i++;
		printf("%8d", *(int *)node->value);
		node = node->next;
		if (node == dlist->tail ) { printf("%10d\n",i);break; }
	}

	printf("\n");
	printf("DupByKey %u elements.\n", listLength(dlist));

	listRelease(mylist);

	return 0;
}
